<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            margin: 50px;
        }
        .lock{
            margin: 30px 0;
        }
        .lock input{
            height: 40px;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            width: 100%;
            outline: none;
            box-sizing: border-box;
            line-height: 5px;
           
        }
        a{
            text-decoration: none;
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="lock">
            <input type="text" placeholder="输入用户名">
        </div>
        <div class="lock">
            <input type="text" placeholder="输入密码">
        </div>
        
        <div class="lock">
            <input type="button" value="登录" style=" background-color:  blue;">
        </div>
        <a href="">忘记密码?</a>
    </div>
</body>
</html>
<script>
    function objToSearchString(obj){
    var str  = ''
    for(var key in obj){
        str += `${key}=${obj[key]}&`;
    }
    return str.slice(0,str.length-1);
}

//封装ajax函数            
function ajax( method, url, params , cb ){
    //1.创建请求对象
    var xhr = new XMLHttpRequest()

    //2.配置请求对象
    xhr.open(method, method == 'get' ? url + "?" + objToSearchString(params) : url );

    //3.设置回调函数
    xhr.onreadystatechange = function(){
        if( xhr.readyState == 4 ){
            cb( JSON.parse(xhr.responseText) )
        }
    }

    //4.发送请求
    //先对post请求设置 content-type 请求头
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xhr.send(  method == 'get' ? null : objToSearchString(params) );
}
    var inputs=document.querySelectorAll(".box .lock input")
    inputs[2].onclick=function(){
        if(inputs[0].value&&inputs[1].value){
            if(/^\d{5}$/.test(inputs[1].value)){
              ajax('get','https://yantianfeng.com/api/register',{username:inputs[0].value,password:inputs[1].value},function(data){
                if( data.code == 200 ){
                            alert('登陆成功');
                        }else{
                        alert('登陆失败!');
                        }
              })
            }else{
                    alert('请输入正确的手机号/密码')
                }
        }else{
                alert('用户名/密码不能为空!')
            }
    }
</script>


